package cn.stylefeng.guns.modular.demo.excel.listener;

import cn.stylefeng.guns.core.exception.BusinessException;
import cn.stylefeng.guns.core.exception.BusinessExceptionEnum;
import cn.stylefeng.guns.dao.IGoodsService;
import cn.stylefeng.guns.dao.ISupplierService;
import cn.stylefeng.guns.dao.entity.Goods;
import cn.stylefeng.guns.dao.entity.Supplier;
import cn.stylefeng.guns.modular.demo.excel.domain.GoodsExcelVO;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
public class GoodsListener implements ReadListener<GoodsExcelVO> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    private List<GoodsExcelVO> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private List<String> keyList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    /**
     * 假设这个是一个DAO，当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
     */
    private IGoodsService goodsService;

    private List<String> errorList;


    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     *
     * @param goodsService
     */
    public GoodsListener(IGoodsService goodsService, List<String> errorList) {
        this.goodsService = goodsService;
        this.errorList = errorList;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. It is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(GoodsExcelVO data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        String supplierCode = data.getCommodityCode();
        if (keyList.contains(supplierCode)) {
            throw new BusinessException(BusinessExceptionEnum.BUSINESS_DATA_REPEAT, "重复的供应商编码" + supplierCode);
        }
        if (goodsService.isExist(supplierCode)) {
            throw new BusinessException(BusinessExceptionEnum.BUSINESS_DATA_REPEAT, "编码" + supplierCode + "已经存在");
        }
        cachedDataList.add(data);
        keyList.add(supplierCode);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
            keyList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) {
        log.error("解析失败，但是继续解析下一行:{}", exception.getMessage());
        // 如果是某一个单元格的转换异常 能获取到具体行号
        // 如果要获取头的信息 配合invokeHeadMap使用
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            log.error("第{}行，第{}列解析异常，数据为:{}", excelDataConvertException.getRowIndex(), excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData());
        }

        if (exception instanceof BusinessException) {
            errorList.add(exception.getMessage());
        }

    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        List<Goods> collect = cachedDataList.stream().map(r -> {

            Goods supplier = new Goods();
            supplier.setCommodityCode(r.getCommodityCode());
            supplier.setPrice(r.getPrice());
            supplier.setVender(r.getVender());
            supplier.setCommoditySpec(r.getCommoditySpec());
            supplier.setCommodityUnit(r.getCommodityUnit());
            supplier.setCommodityName(r.getCommodityName());
            return supplier;
        }).collect(Collectors.toList());
        goodsService.saveBatch(collect);
        log.info("存储数据库成功！");
    }
}
